class Solution {
  public:

    int n, m;
    int dx[4] = {1, -1, 0, 0};
    int dy[4] = {0, 0, -1, 1};

    int rotApple(vector<vector<int> >& grid) {
        n = grid.size(), m = grid[0].size();
        queue<pair<int, int>> q;
        int fresh = 0;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == 2) q.push({i, j});
                else if (grid[i][j] == 1) fresh++;
            }
        }

        if (fresh == 0) return 0;

        int minutes = 0;
        while (!q.empty() && fresh > 0) {
            int levelSize = q.size();
            minutes++;

            for (int _ = 0; _ < levelSize; _++) {
                auto [x, y] = q.front();
                q.pop();
                for(int k=0;k<4;k++)
                {
                    int i=x+dx[k];
                    int j=y+dy[k];
                    if(i>=0&&i<n&&j>=0&&j<m&&grid[i][j]==1) 
                    {
                        grid[i][j]=2;
                        fresh--;
                        q.push({i,j});
                    }
                }
            }

        }

        return fresh?-1:minutes;

    }
};